//
//  KSUInfoItem.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/25.
//  Copyright © 2025 aowang. All rights reserved.
//  定制的一个item 类型

import UIKit
 import Kingfisher
class KSCCLCItem: KSFormHItem {
    // MARK: - 懒加载 lazy
     lazy var icon:UIButton = {
        let v = UIButton()
         v.layer.masksToBounds = true
         v.layer.cornerRadius = 5
         v.setBackgroundImage(UIImage(named: "wenhao"), for: .normal)
        return v
    }()
    var clickableRanges: [NSRange] = [] // 存储每一段文本的范围
    
    var iconTouchClo:(()->())?
    var getNoClo:((String)->())?
    var tapGesture:UITapGestureRecognizer?

    convenience init(appearance: KSFormBaseAppear? = KSFormBaseAppear()) {
        self.init(title: "", appearance: appearance,type:.tempTextView)
        self.setTempTitle("出差流程")
        self.addSubview(icon)
        icon.addTouchUpInSideAction { _ in
            if let clo = self.iconTouchClo {
                clo()
            }
        }
        tpTitleLab.snp.remakeConstraints { make in
            make.left.equalTo(self).offset(widgetLeading)
            make.centerY.equalTo(self)
            make.width.equalTo(70)
        }
        icon.snp.makeConstraints { make in
             make.height.equalTo(22)
            make.width.equalTo(22)
            make.left.equalTo(tpTitleLab.snp.right).offset(3)
            make.centerY.equalTo(self)
        }
        textView.isScrollEnabled = false
        textView.delegate = self
        textView.translatesAutoresizingMaskIntoConstraints = false
        // 添加点击手势
//        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
//        textView.addGestureRecognizer(tapGesture)
     
      
      }
    
    
    func setupContent(rawString:String) {
        // 根据文本是否有内容而显示占位label
        textView.placeHolder = (rawString != "") ? "" : "请选择出差流程"
        if rawString != "" {
            // 添加点击手势
            
            tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
            textView.addGestureRecognizer(tapGesture!)
            textView.isEditable = false

        } else {
            // 移除，提升初次选择的体验感
            if tapGesture.isSome {
                textView.removeGestureRecognizer(tapGesture!)
                textView.isEditable = true
            }
            

        }
        
        
         let paragraphs = rawString.components(separatedBy: "\n")
        
        let attributedString = NSMutableAttributedString()
      
        clickableRanges.removeAll()
        
        // 为每个段落添加下划线和点击范围
        paragraphs.enumerated().forEach { index, text in
            let paragraph = NSMutableAttributedString(string: text)
            
            // 添加下划线样式
            paragraph.addAttribute(
                .underlineStyle,
                value: NSUnderlineStyle.single.rawValue,
                range: NSRange(location: 0, length: text.count)
            )
            
            // 记录每个段落的范围
            let previousLength = attributedString.length
            attributedString.append(paragraph)
            
            // 最后一个段落不加换行符
            if index != paragraphs.count - 1 {
                attributedString.append(NSAttributedString(string: "\n"))
            }
            
            // 保存有效点击范围（排除换行符）
            clickableRanges.append(
                NSRange(location: previousLength, length: text.count)
            )
        }
        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 17), range: NSRange(location: 0, length: attributedString.length))
        
        
        
        let paraph = NSMutableParagraphStyle()
        //将行间距设置为
        paraph.lineSpacing = 7
        paraph.alignment = .right
        
        attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paraph, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(kshex: "1E90FF"), range: NSRange(location: 0, length: attributedString.length))
      
        
        textView.attributedText = attributedString
        self.textView.snp.remakeConstraints { make in
           
            
                make.right.equalTo(self).offset(-self.appearance.contentTrailing + 3)
            make.left.equalTo(self.icon.snp.right).offset(5)
                make.top.equalTo(self).offset(3)
                make.bottom.equalTo(self).offset(-3)
             
        }
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: textView)
        
        // 计算点击位置对应的字符索引
        let layoutManager = textView.layoutManager
        var characterIndex = layoutManager.characterIndex(
            for: location,
            in: textView.textContainer,
            fractionOfDistanceBetweenInsertionPoints: nil
        )
        
        // 防止索引越界
        characterIndex = min(characterIndex, textView.text.unwrap.count - 1)
        
        // 查找匹配的段落
        for (index, range) in clickableRanges.enumerated() {
            if range.contains(characterIndex) {
                let paragraph = textView.attributedText.attributedSubstring(from: range)
                print("点击了第 \(index + 1) 段: \(paragraph.string)")
                if let clo = self.getNoClo {
                    clo(paragraph.string)
                }
                return
            }
        }
    }
    // 禁用原生链接交互
//    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
//        return false
//    }
  
}
import UIKit

class ViewxxxController: UIViewController {
    let textView = UITextView()
    var clickableRanges: [NSRange] = [] // 存储每一段文本的范围
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTextView()
        setupContent()
    }
    
    func setupTextView() {
        textView.isEditable = false
        textView.isScrollEnabled = false
        textView.delegate = self
        textView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textView)
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        textView.addGestureRecognizer(tapGesture)
        
        // 布局代码
        NSLayoutConstraint.activate([
            textView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            textView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            textView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8)
        ])
    }
    
    func setupContent() {
        let rawString = "QU2025-0001\nQU2025-0002\nQU2025-0003\nQU2025-0004"
        let paragraphs = rawString.components(separatedBy: "\n")
        
        let attributedString = NSMutableAttributedString()
        clickableRanges.removeAll()
        
        // 为每个段落添加下划线和点击范围
        paragraphs.enumerated().forEach { index, text in
            let paragraph = NSMutableAttributedString(string: text)
            
            // 添加下划线样式
            paragraph.addAttribute(
                .underlineStyle,
                value: NSUnderlineStyle.single.rawValue,
                range: NSRange(location: 0, length: text.count)
            )
            
            // 记录每个段落的范围
            let previousLength = attributedString.length
            attributedString.append(paragraph)
            
            // 最后一个段落不加换行符
            if index != paragraphs.count - 1 {
                attributedString.append(NSAttributedString(string: "\n"))
            }
            
            // 保存有效点击范围（排除换行符）
            clickableRanges.append(
                NSRange(location: previousLength, length: text.count)
            )
        }
        
        textView.attributedText = attributedString
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: textView)
        
        // 计算点击位置对应的字符索引
        let layoutManager = textView.layoutManager
        var characterIndex = layoutManager.characterIndex(
            for: location,
            in: textView.textContainer,
            fractionOfDistanceBetweenInsertionPoints: nil
        )
        
        // 防止索引越界
        characterIndex = min(characterIndex, textView.text.count - 1)
        
        // 查找匹配的段落
        for (index, range) in clickableRanges.enumerated() {
            if range.contains(characterIndex) {
                let paragraph = textView.attributedText.attributedSubstring(from: range)
                print("点击了第 \(index + 1) 段: \(paragraph.string)")
                return
            }
        }
    }
}

extension ViewxxxController: UITextViewDelegate {
    // 禁用原生链接交互
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        return false
    }
}
